// ****************************************************************
// Copyright 2012, Stephan Burguchev
// e-mail: me@sburg.net
// ****************************************************************
// *
using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using Version = Updater.Utils.Version;

namespace Updater.Common
{
    [XmlRoot("change-log-record")]
    public class ChangeLogRecord : IXmlSerializable
    {
        public ChangeLogRecord(Version version, string title, string description)
        {
            if (version == null)
            {
                throw new ArgumentNullException("version");
            }

            if (title == null)
            {
                throw new ArgumentNullException("title");
            }

            if (description == null)
            {
                throw new ArgumentNullException("description");
            }

            this.Version = version;
            this.Title = title;
            this.Description = description;
        }

        public ChangeLogRecord()
        {
        }

        public string Description { get; private set; }

        public string Title { get; private set; }

        public Version Version { get; private set; }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() !=
                this.GetType())
            {
                return false;
            }

            return this.@equals((ChangeLogRecord)obj);
        }

        public override int GetHashCode()
        {
            return this.Version != null
                       ? this.Version.GetHashCode()
                       : 0;
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            var e = (XElement)XNode.ReadFrom(reader);

            this.Version = Version.Parse(e.Attribute("version").Value);
            this.Description = e.Element("description").Value;
            this.Title = e.Element("title").Value;
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("version", this.Version.ToString());
            writer.WriteElementString("title", this.Title);
            writer.WriteElementString("description", this.Description);
        }

        protected bool equals(ChangeLogRecord other)
        {
            return Equals(this.Version, other.Version);
        }
    }
}
